<template>
  <el-dialog
    title="添加用户"
    :visible="visible"
    width="50%"
    @close="onDialogClose"
  >
    <!-- 绑定的form表单数据 -->
    <el-form ref="addUsersForm" :rules="addUsersFormRules" :model="addUsersForm" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model.trim="addUsersForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model.trim="addUsersForm.password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model.trim="addUsersForm.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model.trim="addUsersForm.mobile" placeholder="请输入手机号" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onDialogClose">取 消</el-button>
      <el-button type="primary" @click="onAdd">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addUser } from '@/api/user'
export default {
  model: {
    prop: 'visible'
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      // 添加的表单数据
      addUsersForm: {
        username: '拉普拉斯',
        password: '123456',
        email: '2233wahaha@163.com',
        mobile: '13823465798'
      },
      // 表单的校验规则
      addUsersFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, message: '邮箱格式不正确', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, message: '手机号格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  created() {

  },

  methods: {
    // 对话框关闭，表单重置
    onDialogClose() {
      this.$emit('input', false)
      this.$refs.addUsersForm.resetFields()
    },
    // 点击确定
    async onAdd() {
      await this.$refs.addUsersForm.validate()
      try {
        // 发送请求添加用户
        await addUser(this.addUsersForm)
        this.$message.success('添加成功！')
        this.$emit('success')
        this.onDialogClose()
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style scoped lang='scss'>

</style>
